<?php

namespace qore_base\cli;
use \Qore;

/**
 * @author Samuel Nogueira <samuel.nogueira.dev@gmail.com>
 */
class CliHelper {
	protected static $boxHorizontalPadding = 1;
	protected static $boxVerticalPadding = 0;
	protected static $boxHorizontalBorder = '-';
	protected static $boxVerticalBorder = '|';
	protected static $boxCorner = '+';
	protected static $tabSize = 4;

	public static function box($text, $options = array()) {
		$out = '';
		$title = Qore::vget($options, 'title');
		$text = static::tabsToSpaces($text, static::$tabSize);
		$width = static::maxWidth("$title\n$text");
		$verticalPadding = Qore::vget($options, 'verticalPadding', static::$boxVerticalPadding);
		$horizontalPadding = Qore::vget($options, 'horizontalPadding', static::$boxHorizontalPadding);
		$verticalBorder = Qore::vget($options, 'verticalBorder', static::$boxVerticalBorder);
		$horizontalBorder = Qore::vget($options, 'horizontalBorder', static::$boxHorizontalBorder);
		$corner = Qore::vget($options, 'cornel', static::$boxCorner);

		$szHorizontalBorder = $corner.str_repeat($horizontalBorder, $width + $horizontalPadding * 2).$corner."\n";
		$szVerticalPadding = str_repeat(static::_boxLine(' ', $width, $horizontalPadding, $verticalBorder), $verticalPadding);

		$out .= $szHorizontalBorder;
		if ($title) {
			$out .= static::_boxLine($title, $width, $horizontalPadding, $verticalBorder, STR_PAD_BOTH);
			$out .= $szHorizontalBorder;
		}
		$out .= $szVerticalPadding;
		foreach (explode("\n", $text) as $line) {
			$out .= static::_boxLine($line, $width, $horizontalPadding, $verticalBorder, STR_PAD_RIGHT);
		}
		$out .= $szVerticalPadding;
		$out .= $szHorizontalBorder;

		return $out;
	}

	/**
	 * Returns the max characters in one line for a given string
	 *
	 * @param string $multilineText
	 * @return int
	 */
	public static function maxWidth($multilineText) {
		$max = 0;
		foreach (explode("\n", $multilineText) as $line) {
			$count = strlen($line);
			if ($count > $max)
				$max = $count;
		}
		return $max;
	}

	/**
	 * @author Zhay
	 * @link http://www.phpshare.org/scripts/Convert-Tabs-to-Spaces
	 */
	public static function tabsToSpaces($text, $spaces = 4) {
		// Explode the text into an array of single lines
		$lines = explode("\n", $text);

		// Loop through each line
		foreach ($lines as $line) {
			// Break out of the loop when there are no more tabs to replace
			while (false !== $tab_pos = strpos($line, "\t")) {
				// Break the string apart, insert spaces then concatenate
				$start = substr($line, 0, $tab_pos);
				$tab = str_repeat(' ', $spaces - $tab_pos % $spaces);
				$end = substr($line, $tab_pos + 1);
				$line = $start.$tab.$end;
			}

			$result[] = $line;
		}

		return implode("\n", $result);
	}

	protected static function _boxLine($text, $width, $padding, $border = '|', $padType = STR_PAD_RIGHT) {
		$szPadding = str_repeat(' ', $padding);
		return $border.$szPadding.str_pad($text, $width, ' ', $padType).$szPadding.$border."\n";
	}

}
